/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof.wget;

import Downloader.CoreDownloader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Carlos Pinheiro
 */
public class DownloaderExecutor implements Runnable
{

    private ResizeableSemaphore rs;

    public DownloaderExecutor() throws InterruptedException
    {
        this.rs = DownloadersBalancer.getInstance().getDownloadersSemaphore();
        this.rs.acquire();
    }

    @Override
    public void run()
    {
        WebResource wr = ToDownloadQueue.getInstance().poll();
        if (wr != null)
        {
            String sUrl = wr.getSourceUrl().toString();
            System.out.println("Downloading " + sUrl + " ...");
            try
            {

                CoreDownloader d = new CoreDownloader();
                d.coreDownloadFile(sUrl, WebResource.getBasePath(), 100);
                d.downloadFile();
                wr.setLocalPath(d.getFullLocalPathFile());
                DownloadedSet.getInstance().add(wr.getSourceUrl().toString());

                if (d.isPagetoParser())
                {
                    ToParseQueue.getInstance().offer(wr);
                }

            }
            catch (Exception ex)
            {
                Logger.getLogger(DownloaderExecutor.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("Downloaded: " + sUrl + ".");
        }

        this.rs.release();
    }
}
